package so.ifl.mybatis.plugins;

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.FastResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.RowBounds;

import so.ifl.commons.tools.ReflectUtil;

/**
 * @author atyuan.lu
 * <mailto:atyuan.lu@gmail.com>
 * @since 2011-4-7
 **/
@Intercepts( {@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DiclectResultSetHandlerInterceptor implements Interceptor {

	
	public Object intercept(Invocation invocation) throws Throwable {
		FastResultSetHandler fastResultSetHandler = (FastResultSetHandler)invocation.getTarget();
		RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(fastResultSetHandler,"rowBounds");
		
		if (rowBounds.getLimit() > 0
		        && rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)
		{
			//当使用分页查询时，将rowBounds置为空，使用不用逻辑分页
		    ReflectUtil.setFieldValue(fastResultSetHandler, "rowBounds", new RowBounds());
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties arg0) {
		// do nothing

	}

}
